#include <memory>
#include <chrono>
#include "HeartbeatTask.h"
#include "../Request/Request.h"
#include "../Request/RequestManager.h"
#include "../Util/SingletonTemplate.h"
#include "../Session/TcpSession.h"
#include "../Util/config.h"
HeartbeatTask::HeartbeatTask(/* args */)
{
}

HeartbeatTask::~HeartbeatTask()
{
    Stop();
}


void HeartbeatTask::SendHeartbeatThread()
{
    auto start = std::chrono::high_resolution_clock::now();
    int duration = -1;
    while (running_)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        if (-1 == duration)
        {
            duration = g_heartbeatinveral;
        }
        else
        {
            auto duration_secondes = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::high_resolution_clock::now() - start);
            duration = static_cast<int>(duration_secondes.count());
        }
        
        if (duration < g_heartbeatinveral)
        {
            continue;
        }
        
        //todo 生成心跳指令
        uint8_t *buffer = nullptr;
        size_t sz = 0;

        // todo此处有bug,  buffer需要深拷贝到函数对象中,次数仅仅作为展示.功能用途
        std::shared_ptr<Request> sp_Request = std::make_shared<Request>([buffer, sz]()->bool{
            if (0 != SingletonTemplate<TcpSession>::GetInstance()->Send(buffer,sz))
            {
                return false;
            }
            
            return true;
            }, g_overtime_tcp, g_retry_tcp, g_serial);
        SingletonTemplate<RequestManager>::GetInstance()->AddRequest(sp_Request);

        start = std::chrono::high_resolution_clock::now();
    }
    
}

void HeartbeatTask::Start()
{
    running_ = true;
    thread_ = std::thread(&HeartbeatTask::SendHeartbeatThread, this);
}

void HeartbeatTask::Stop()
{
    running_ = false;
    thread_.join();
}
